﻿using Oracle.DataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;

namespace DbStreamConverter.Odp
{
    public class OdpDbProvider : DbProvider
    {
        public OdpDbProvider()
        {
            Factory = new Oracle.DataAccess.Client.OracleClientFactory();
        }

        public override void BulkCopy<T>(IEnumerable<T> items, string destinationTableName, List<string> propList, int timeout = 0)
        {
            destinationTableName = destinationTableName ?? typeof(T).Name;
            using (OracleBulkCopy bulkCopy = new OracleBulkCopy(Config.ConnectionString))
            {
                foreach (var prop in propList)
                {
                    bulkCopy.ColumnMappings.Add(prop, prop);
                }
                bulkCopy.DestinationTableName = destinationTableName;
                if (timeout > 0) bulkCopy.BulkCopyTimeout = timeout;
                
                bulkCopy.WriteToServer(new BulkCopyDataReader<T>(items, propList));
            }

        }

        public override void CreateTempTable(string tableName, string seletStat)
        {
            DbConnection cnct = Factory.CreateConnection();
            cnct.ConnectionString = Config.ConnectionString;
            DbCommand cmd = cnct.CreateCommand();
            cmd.CommandText = string.Format("create table {0} as select * from ({1}) source where 1=0", tableName, seletStat);

            try
            {
                cnct.Open();
                cmd.ExecuteNonQuery();
            }
            finally
            {
                cnct.Close();
            }
        }
    }
}
